package com.zenithsun.common.dao;

import java.sql.Connection;
import java.util.List;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.hibernate.SQLQuery;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate4.SessionFactoryUtils;

import com.syzg.base.merge.model.Person;
import com.syzg.common.dao.impl.BaseDAOHibernate;

/**
 * 拓展一部分原生态SQL的DAO实现，针对hibernate
 * 
 * @author wanglei@enersun.com.cn
 */
public abstract class NativeSQLDaoHibernate<T> extends BaseDAOHibernate<T>
		implements NativeSQLDao<T> {

	@Resource
	private SessionFactory sessionFactory;

	@Override
	public List<T> queryBySQL(SQLQuery query) throws Exception {
		return query.list();
	}

	/**
	 * 查询数量
	 * 
	 * @param query
	 *            {@link SQLQuery}
	 * @return int
	 * @throws Exception
	 */
	public int getCountBySQL(SQLQuery query) throws Exception {
		Long count = Long.parseLong(query.uniqueResult().toString());
		return count.intValue();
	}

	/**
	 * 获取JDBC连接
	 * 
	 * @return int
	 * @throws Exception
	 */
	public Connection getConnection() throws Exception {
		return getDataSource().getConnection();
	}

	/**
	 * 获取数据源
	 * @return
	 */
	private DataSource getDataSource() {
		return SessionFactoryUtils.getDataSource(sessionFactory);
	}
	
	@Override
	public Person getPersonByPersionId(String account) throws Exception{
		SQLQuery query =getSession().createSQLQuery("SELECT P.* FROM PERSON P WHERE P.ACCOUNT=?");
		query.addEntity(Person.class);
		query.setParameter(0,account);
		List personList= query.list();
		if(personList!=null&&personList.size()>0){
			return (Person)personList.get(0);
		}
		return null;
	}
}